package com.andy.nature.ui.activity

import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.andy.common.base.BaseVMActivity
import com.andy.common.extend.setOnIMClickListener
import com.andy.nature.databinding.ActivityMainBinding
import com.andy.nature.ui.adapter.MainPagerAdapter
import com.andy.nature.view.TabView
import com.andy.nature.vm.MainViewModel

/**
 * Author:Andy
 * Date:2023/3/20 17:51
 * Description:MainActivity
 */
class MainActivity : BaseVMActivity<ActivityMainBinding, MainViewModel>() {
    private lateinit var mAdapter: MainPagerAdapter

    override fun viewModelClass(): Class<MainViewModel> {
        return MainViewModel::class.java
    }

    override fun getViewBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun initObserve() {
    }

    override fun initData() {
        mBinding?.apply {
            mAdapter = MainPagerAdapter(this@MainActivity)
            viewPager.adapter = mAdapter
            tab1.clearBadge()
            tab2.setBadge(3)
            tab3.setBadge(18)
            tab4.setBadge(100)
        }
    }

    override fun initAction() {
        mBinding?.apply {
            viewPager.registerOnPageChangeCallback(object : OnPageChangeCallback() {
                override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                }

                override fun onPageSelected(position: Int) {
                    switchTab(position)
                }

                override fun onPageScrollStateChanged(state: Int) {
                }
            })
            tab1.setOnIMClickListener {
                switchTab(0)
                viewPager.setCurrentItem(0, true)
            }
            tab2.setOnIMClickListener {
                switchTab(1)
                viewPager.setCurrentItem(1, true)
            }
            tab3.setOnIMClickListener {
                switchTab(2)
                viewPager.setCurrentItem(2, true)
            }
            tab4.setOnIMClickListener {
                switchTab(3)
                viewPager.setCurrentItem(3, true)
            }
        }
    }


    fun switchTab(position: Int) {
        mBinding?.apply {
            for (i in 0..3) {
                val tabView = tabLayout.getChildAt(i) as TabView
                tabView.let {
                    if (position == i) {
                        tabView.setSelect(i)
                    } else {
                        tabView.setUnselect(i)
                    }
                }
            }
        }
    }
}